package com.zsj.juc.lock;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/17 13:14
 * @description 解决ABA问题
 */


public class CasAQuestion {

    private static final Logger log = LoggerFactory.getLogger(CasAQuestion.class);

    public static void main(String[] args) {

        Resource resource = new Resource(1);
        AtomicReference<Resource> stampedReference
                = new AtomicReference<>(resource);//初始化原子资源

        log.info("老公上班去了");
        //t1去修改
        new Thread(() -> {
            log.info("哈哈哈老王来偷家咯 {}", Thread.currentThread().getName());
            Resource r2 = new Resource(2);
            stampedReference
                    .compareAndSet(resource,
                            r2);
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            log.info("已经是老王的形状了");
            //释放
            stampedReference.compareAndSet(r2, resource);
            log.info("老王回家了");
        }, "wang").start();

        //保证t1先执行
        try {
            TimeUnit.MILLISECONDS.sleep(1500);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }

        new Thread(() -> {
            log.info("老公回家了");
            Resource r3 = new Resource(3);
            log.info("老公检查 ing");
            boolean b = stampedReference.compareAndSet(resource, r3);
            log.info(!b ? "老婆变了!" : "老婆忠诚!");
        }, "t2").start();


    }
}
